package com.li.taskcenter.controller.quartz;

import com.alibaba.fastjson.JSON;
import com.li.taskcenter.domain.taskcenter.TaskInfo;
import com.li.taskcenter.mapper.taskcenter.TaskDefineMapper;
import org.quartz.JobExecutionContext;
import org.quartz.Trigger;
import org.quartz.impl.JobExecutionContextImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description：任务执行总类继承 QuartzJobBean重写 executeInternal()
 * @Author：LiDong
 * @Create：2020/12/15
 * @Version：1.0.0
 */
public class MyTask extends QuartzJobBean {

    private static final Logger logger = LoggerFactory.getLogger(MyTask.class);

    @Autowired
    private TaskDefineMapper taskDefineMapper;

    /**
     * @return void
     * @Author LiDong
     * 从jobExecutionContext 中拿出当前task的code
     * @Date 22:07 2020/12/22
     * @Param [jobExecutionContext]
     **/
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {
        //TODO 这里写定时任务的执行逻辑
        JobExecutionContextImpl jobDetail = ((JobExecutionContextImpl) jobExecutionContext);
        Trigger trigger = jobDetail.getTrigger();
        // 获得任务编码
        String taskCode = trigger.getJobKey().getName();
        dealJob(taskCode);
    }

    /**
     * @return void
     * @Author LiDong
     * @Description //TODO 执行url的具体逻辑
     * @Date 21:33 2020/12/23
     * @Param [taskcode]
     **/
    private void dealJob(String taskcode) {
        Map<String, String> map = new HashMap<>(1);
        map.put("taskcode", taskcode);
        TaskInfo taskDefine = taskDefineMapper.getTaskDefine(map);
        if (Objects.nonNull(taskDefine)) {
            String url = taskDefine.getUrl();
            String method = taskDefine.getMethod();
            String urlparams = taskDefine.getUrlparams();
            Map<String, String> param = JSON.parseObject(urlparams, Map.class);

            logger.info("动态的定时任务执行时间：" + new Date());
        }
    }
}
